var { User } = require("./../models.js");
const Token = require("../modules/Token");
const fs = require("fs");
const path = require("path");
const { Op } = require("sequelize");
const md5 = require("md5");

module.exports.regist = async (req, res, next) => {
  let { username, password } = req.body;
  const users = await User.findAll({
    where: {
      username,
    },
  });
  if (!users.length) {
    const user = await User.create({ username, password: md5(password) });
    res.sendResult(user, 0, "创建成功");
  } else {
    res.sendResult(null, 1, "用户存在");
  }
};

module.exports.login = async (req, res, next) => {
  let { username, password } = req.body;
  console.log(md5(password));
  const users = await User.findAll({
    where: {
      username,
      password: md5(password),
    },
    attributes: {
      exclude: ["password"],
    },
  });
  if (users.length) {
    let secretOrPrivateKey = "This is perfect projects.";
    var token = Token.encrypt(
      { username, password },
      secretOrPrivateKey,
      60 * 60 * 24 * 7
    ); //60 * 60 * 24 * 7一周过期
    token = "bearer " + token;
    return res.sendResult({ user: users[0], token }, 0, "登录成功！");
  } else {
    res.sendResult(null, 1, "账号或密码不匹配");
  }
};

module.exports.getUserInfo = async (req, res, next) => {
  let { user } = req.query;
  if (user) {
    res.sendResult(user, 0, "获取成功");
  } else {
    res.sendResult(null, 0, "获取失败");
  }
};

module.exports.deleteUser = async (req, res) => {
  const { userId } = req.body;
  try {
    await User.destroy({
      where: {
        id: userId,
      },
    });
    res.sendResult(null, 0, "删除评论成功");
  } catch (error) {
    res.sendResult(error, 1, "删除评论成功失败");
  }
};

module.exports.findUser = async (req, res) => {
  const {
    page = { pageNumber: 1, pageSize: 10 },
    pageSize,
    username,
  } = req.body;
  try {
    const filterParams = {
      username: {
        [Op.like]: "%" + (username ? username : "") + "%",
      },
    };
    const users = await User.findAndCountAll({
      limit: pageSize ? pageSize : page.pageSize,
      offset: pageSize
        ? pageSize * (page - 1)
        : page.pageSize * (page.pageNumber - 1),
      where: filterParams,
    });
    res.sendResult(users, 0, "查找成功");
  } catch (error) {
    res.sendResult(error, 1, "查找失败");
  }
};

module.exports.addDownload = async (req, res) => {
  const { articleIds, userId } = req.body;
  let downloads = [];
  if (articleIds && articleIds.length) {
    downloads = articleIds;
  }
  const user = await User.findByPk(userId);
  try {
    const users = await User.update(
      { downloads: downloads.join(",") },
      {
        where: {
          id: userId,
        },
      }
    );
    res.sendResult(users, 0, "更新成功");
  } catch (error) {
    res.sendResult(error, 1, "更新失败");
  }
};

module.exports.updatePassword = async (req, res, next) => {
  let { username, password, newPasswod } = req.body;
  const users = await User.findAll({
    where: {
      username,
      password,
    },
  });
  if (users.length) {
    const user = await User.update(
      { password: newPasswod },
      {
        where: {
          username,
          password,
        },
      }
    );
    res.sendResult(null, 0, "修改成功");
  } else {
    res.sendResult(null, 1, "账号或密码不匹配");
  }
};

module.exports.updateIcon = async (req, res) => {
  let { icon_url } = req.body;
  const user = req.query;

  if (!user.user.icon_url.includes("default")) {
    fs.unlink(path.resolve(user.user.icon_url), (err) => {
      console.log(err);
    });
  }
  try {
    const result = await User.update(
      { icon_url },
      {
        where: {
          id: user.user.id,
        },
      }
    );
    res.sendResult(null, 0, "修改成功");
  } catch (error) {
    res.sendResult(error, 1, "更新头像失败");
  }
};
